package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.BaiduMapUtils;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private BaiduMapUtils baiduMapUtils;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        // 处理业务异常
        Long addressBookId = ordersSubmitDTO.getAddressBookId();
        // 用户地址为空，不能下单
        AddressBook address = addressBookMapper.getById(addressBookId);
        if(address == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        // 校验配送距离
        String userAddress = address.getDetail();
        if (!baiduMapUtils.checkDeliveryRange(userAddress)) {
            throw new OrderBusinessException(MessageConstant.BEYOND_DELIVERY_RANGE);
        }
        // 购物车数据为空，不能下单
        ShoppingCart shoppingCart = new ShoppingCart();
        Long userId = BaseContext.getCurrentId();
        shoppingCart.setUserId(userId); // 获取用户 ID 这一块
        List<ShoppingCart> listShoppingCart = shoppingCartMapper.listShoppingCart(shoppingCart);
        if(listShoppingCart == null || listShoppingCart.size() == 0){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        // 向订单表插入一条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);  // 先拷贝一部分
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(address.getPhone());
        orders.setConsignee(address.getConsignee());
        orders.setUserId(userId);
        orders.setAddress(address.getDetail());

        orderMapper.insertData(orders);

        List<OrderDetail> orderDetailList =new ArrayList<>();  // 存放订单数据，方便批量插入
        // 向订单明细表中插入多条数据
        for (ShoppingCart cart : listShoppingCart) {
            OrderDetail orderDetail = new OrderDetail();    // 订单明细
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());   // 设置订单明细关联的 ID
            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetailList); // 批量插入多条数据

        // 清除购物车数据
        shoppingCartMapper.deleteShoppingCart(userId);
        // 封装并返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .build();

        return orderSubmitVO;
    }


    /**
     * 再来一单
     * @param id
     */
    @Override
    public void submitOrderOneMore(Long id) {
        // 根据 ID 查询订单详情
        List<OrderDetail> details = orderDetailMapper.selectOrderDetailList(id);
        // 根据 ID 查询订单包含菜品
        List<ShoppingCart> shoppingCarts = details.stream().map(x -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(x, shoppingCart, "id");    // 拷贝除了 ID 以外的字段
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;
        }).collect(Collectors.toList());    // 将处理结果收集为列表

        // 将购物车对象批量添加到数据库
        shoppingCartMapper.insertBatch(shoppingCarts);
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
//        // 当前登录用户id
//        Long userId = BaseContext.getCurrentId();
//        User user = userMapper.getById(userId);
//
//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
//
//        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
//        vo.setPackageStr(jsonObject.getString("package"));
        log.info("跳过微信支付，支付成功");

        paySuccess(ordersPaymentDTO.getOrderNumber());

        return new OrderPaymentVO();
    }

    /**
     * 用户查询历史订单
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult selectUserOrder(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        // 设置 DTO 其他字段
        Long userId = BaseContext.getCurrentId();
        ordersPageQueryDTO.setUserId(userId);
        Page<OrderVO> list = orderMapper.selectUserOrder(ordersPageQueryDTO, userId);
        // 查询菜品明细
        if(list != null && list.size() > 0) {
            for (OrderVO orderVO : list) {
                Long orderId = orderVO.getId();
                List<OrderDetail> details = orderDetailMapper.selectOrderDetailList(orderId);
                orderVO.setOrderDetailList(details);
            }
        }
        assert list != null;
        return new PageResult(list.getTotal(), list.getResult());
    }

    /**
     * 支付成功，修改订单状态
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
        // 通过 websocket 向客户端推送消息    type orderId content
        Map map = new HashMap();
        map.put("type", 1);  // 1.来单  2.催单
        map.put("orderId", ordersDB.getId());
        map.put("content", "订单号" + outTradeNo);

        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);
    }

    /**
     * 搜索订单
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult selectOrder(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> list = orderMapper.selectOrder(ordersPageQueryDTO);
        // 部分订单状态，需要额外返回订单菜品信息，将Orders转化为OrderVO
        List<OrderVO> orderVOList = getOrderVOList(list);
        return new PageResult(list.getTotal(), orderVOList);
    }

    private List<OrderVO> getOrderVOList(Page<Orders> page) {
        // 需要返回订单菜品信息，自定义OrderVO响应结果
        List<OrderVO> orderVOList = new ArrayList<>();

        List<Orders> ordersList = page.getResult();
        if (!CollectionUtils.isEmpty(ordersList)) {
            for (Orders orders : ordersList) {
                // 将共同字段复制到OrderVO
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                String orderDishes = getOrderDishesStr(orders);

                // 将订单菜品信息封装到orderVO中，并添加到orderVOList
                orderVO.setOrderDishes(orderDishes);
                orderVOList.add(orderVO);
            }
        }
        return orderVOList;
    }

    /**
     * 根据订单id获取菜品信息字符串
     *
     * @param orders
     * @return
     */
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderDetailMapper.selectOrderDetailList(orders.getId());

        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }

    /**
     * 根据 ID 查询订单
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public OrderVO selectOrderDetails(Long id) {
        // 查询订单菜品信息
        Orders orders = orderMapper.selectOrderDish(id);
        // 查询订单详情
        List<OrderDetail> detailList = orderDetailMapper.selectOrderDetailList(id);

        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(detailList);

        return orderVO;
    }

    /**
     * 接单，更改订单状态
     * @param ordersConfirmDTO
     */
    @Override
    public void acceptOrder(OrdersConfirmDTO ordersConfirmDTO) {
        Long orderId = ordersConfirmDTO.getId();
        Integer orderStatus = Orders.CONFIRMED;
        orderMapper.acceptOrder(orderId, orderStatus);
    }

    /**
     * 拒单，返回拒单原因
     * @param ordersRejectionDTO
     */
    @Override
    public void rejectOrder(OrdersRejectionDTO ordersRejectionDTO) {
        // 获取订单
        Orders orders = orderMapper.getOrder(ordersRejectionDTO.getId());
        // 获取订单支付状态
        Integer status = orders.getPayStatus();

        // 订单只有存在且状态为 2（待接单）才可以拒单
        if(!orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 如果用户已付款那么需要退款
        if(status.equals((Integer) Orders.PAID)) {
//            weChatPayUtil.refund(
//                    ordersDB.getNumber(), //商户订单号
//                    ordersDB.getNumber(), //商户退款单号
//                    new BigDecimal(0.01),//退款金额，单位 元
//                    new BigDecimal(0.01));//原订单金额*/
            orders.setPayStatus(Orders.REFUND);
        }
        // new 一个新对象提升效率
        Orders order = new Orders();
        order.setId(orders.getId());
        order.setStatus(Orders.CANCELLED);
        order.setPayStatus(Orders.REFUND);
        order.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        order.setCancelTime(LocalDateTime.now());
        orderMapper.update(order);
    }

    /*    业务规则：
    - 待支付和待接单状态下，用户可直接取消订单
    - 商家已接单状态下，用户取消订单需电话沟通商家
    - 派送中状态下，用户取消订单需电话沟通商家
    - 如果在待接单状态下取消订单，需要给用户退款
    - 取消订单后需要将订单状态修改为“已取消 */
    /**
     * 用户取消订单
     * @param id
     */
    @Override
    public void userCancelOrder(Long id) {
        // 获取订单
        Orders orders = orderMapper.getOrder(id);
        // 校验订单是否存在
        if(orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 获取订单状态
        Integer status = orders.getStatus();
        // 校验订单状态.商家已接单状态下，用户取消订单需电话沟通商家,此时抛出异常.
        if(status > (Integer)Orders.TO_BE_CONFIRMED ) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 待支付和待接单状态下，用户可直接取消订单, 同时商家退款
        Integer cancelled = Orders.CANCELLED;
        Integer refund = Orders.REFUND;
        if(status.equals(Orders.PENDING_PAYMENT) || status.equals(Orders.TO_BE_CONFIRMED)) {
            //调用微信支付退款接口
/*            weChatPayUtil.refund(
                    ordersDB.getNumber(), //商户订单号
                    ordersDB.getNumber(), //商户退款单号
                    new BigDecimal(0.01),//退款金额，单位 元
                    new BigDecimal(0.01));//原订单金额*/
            orders.setPayStatus(refund);
        }
        // 更新订单状态
        orders.setStatus(cancelled);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 用户催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        // 获取订单
        Orders orders = orderMapper.getOrder(id);
        // 校验订单是否存在
        if(orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 构造 JSON 对象，通过 websocket 向客户端推送消息    type orderId content
        Map map = new HashMap();
        map.put("type", 2);  // 1.来单  2.催单
        map.put("orderId", id);
        map.put("content", "订单号" + orders.getNumber());

        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);
    }

    /**
     * 商家取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void adminCancelOrder(OrdersCancelDTO ordersCancelDTO) {
        // 获取订单
        Orders orders = orderMapper.getOrder(ordersCancelDTO.getId());
        // 获取订单状态
        Integer status = orders.getPayStatus();
        // 如果用户已支付，需要退款
        if(status.equals((Integer) Orders.PAID)) {
//            weChatPayUtil.refund(
//                    ordersDB.getNumber(), //商户订单号
//                    ordersDB.getNumber(), //商户退款单号
//                    new BigDecimal(0.01),//退款金额，单位 元
//                    new BigDecimal(0.01));//原订单金额*/
            orders.setPayStatus(Orders.REFUND);
        }
        // new一个 order 避免更新不需要的字段，提高效率及其安全性
        Orders order = new Orders();
        order.setId(ordersCancelDTO.getId());
        order.setStatus(Orders.CANCELLED);
        order.setCancelReason(ordersCancelDTO.getCancelReason());
        order.setCancelTime(LocalDateTime.now());
        orderMapper.update(order);
    }

    /**
     * 统计各个状态的订单数量
     * @return
     */
    @Override
    public OrderStatisticsVO orderStatistics() {
        // 单个查询 2、3、4 每个状态的数量
        Integer toBeConfirmed = orderMapper.orderStatistics(Orders.TO_BE_CONFIRMED);
        Integer confirmed = Orders.CONFIRMED;
        Integer deliveryInProgress = Orders.DELIVERY_IN_PROGRESS;
        // 封装到一起
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);

        return orderStatisticsVO;
    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void deliveryOrders(Long id) {
        Orders ordersDB = orderMapper.getOrder(id);
        // 校验订单是否存在并且状态为已接单
        if(ordersDB == null || !ordersDB.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders order = new Orders();
        order.setId(ordersDB.getId());
        order.setStatus(Orders.DELIVERY_IN_PROGRESS);
        order.setEstimatedDeliveryTime(LocalDateTime.now().plusMinutes(30));  // 预计送达时间 = 当前时间 + 30分钟
        orderMapper.update(order);
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void completeOrders(Long id) {
        Orders ordersDB = orderMapper.getOrder(id);
        // 判断订单是否存在并且为派送中
        if(ordersDB == null || !ordersDB.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders order = new Orders();
        order.setId(ordersDB.getId());
        order.setStatus(Orders.COMPLETED);
        order.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(order);
    }
}
